import React, { useEffect, useState,useRef,useCallback} from 'react'
import { Input, Button, Table, Switch,Pagination } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { getUsersList,updateState,deleteUsers} from '../../api/user';
import { FormOutlined,DeleteOutlined, SettingOutlined} from '@ant-design/icons';
// 引入模块框表单组件
import AddOrUpdate from './components/add-or-update'
import SetRoles from './components/set-roles';
export default function Users() {
  let [loading,setLoading] = useState(false)
  // 创建子组件ref实例
  let AddOrUpdateRef = useRef<any>();
  let SetRolesRef = useRef<any>()
  // 查询参数：
  let [query, setQuery] = useState("");
  // 当前页面
  let [pagenum, setPagenum] = useState(1);
  // 每一显示几条数据
  let [pagesize, setPageSize] = useState(5);
  // 表格数据
  let [data, setData] = useState<DataTable[]>([]);
  // 数据总数
  let [total,setTotal] = useState(0);
  // 缓存over函数
  let over = useCallback(()=>{
      getDateList();
  },[pagenum,query,pagesize])
  // 修改用户状态
  let changeState = async (value:boolean,id:number)=>{
    let res = await updateState(id,value);
    console.log(res)
    if(res.data.meta.status === 200){
       getDateList();
    }
  }
  // 删除用户
  let removeUser =async (id:number)=>{
    let res = await deleteUsers(id);
    if(res.data.meta.status===200){
      getDateList();
    }
  }
  // 定义表格每一列
  let columns: ColumnsType<DataTable> = [
    {
      dataIndex: "id",
      title: "用户id",
      width:80
    },
    {
      dataIndex: "username",
      title: "用户名",
      width:100
    },
    {
      dataIndex: "email",
      title: "邮箱",
    },
    {
      dataIndex: "mobile",
      title: "电话",
    },
    {
      dataIndex: "role_name",
      title: "角色", 
      width:150
    },
    {
      dataIndex: "mg_state",
      title: "状态",
      render: (text,record) => {
        return <Switch checked={text} onChange={(value:boolean)=>changeState(value,record.id)}/>
      }
    },
    {
      dataIndex: "action",
      title: "操作",
      width:400,
      render(text, record:DataTable) {
        return (
          <>
           <Button type="primary" icon={<FormOutlined/>} size='small' onClick={()=>{
            // 显示子组件模态框并将当前用户信息传递给子组件
                AddOrUpdateRef.current.init(record);
           }}>
            编辑
          </Button> &nbsp; &nbsp;
          <Button type="primary" danger icon={<DeleteOutlined />} size='small' onClick={()=>removeUser(record.id)}>
            删除
          </Button>&nbsp; &nbsp;
          <Button type="primary" icon={<SettingOutlined />} size='small' onClick={()=>{
            SetRolesRef.current.init(record)
          }}>
            分配角色
          </Button>
          </>
        )
      }
    }
  ]
  let getDateList = ()=>{
    setLoading(true)
      // 发送请求获取用户列表
      getUsersList({ query, pagenum, pagesize }).then(res => {
        if(res.data.meta.status!==200){
          return
        }
        setData(res.data.data.users)
        setTotal(res.data.data.total)
        setLoading(false)
      })
  }
  useEffect(() => {
    getDateList();
  }, [ query, pagenum, pagesize ])

  // 显示模态框
  let showModel = ()=>{
    AddOrUpdateRef.current.init();
  }
  return (
    <div>
      <div style={{ display: "flex" }}>
        <div style={{ width: "300px" }}>
          <Input.Search onSearch={(e)=>{
             setQuery(e)
          }}/>
        </div>
        <div style={{ marginLeft: "10px" }}>
          <Button type='primary' onClick={showModel}>添加用户</Button>
        </div>
      </div>
      <div style={{ margin: '20px 0' }}>
        <Table columns={columns} dataSource={data} bordered={true} rowKey='id' pagination={false} loading={loading}/>
      </div>
      <div>
        <Pagination current={pagenum} pageSize={pagesize} total={total} showSizeChanger showQuickJumper pageSizeOptions={[5,10,15,20]} onChange={(page,size)=>{
          setPagenum(page);
          setPageSize(size);
        }}/>
      </div>
      <AddOrUpdate ref={AddOrUpdateRef} over={()=>{
          getDateList();
      }}/>
      <SetRoles ref={SetRolesRef} over={over}/>
    </div>
  )
}
